package com.example.mobiletest.ui

import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mobiletest.R
import com.example.mobiletest.model.Booking
import com.example.mobiletest.ui.adapter.SegmentAdapter
import com.example.mobiletest.ui.viewmodel.BookingViewModel
import java.text.SimpleDateFormat
import java.util.*

class BookingListActivity : AppCompatActivity() {

    private lateinit var viewModel: BookingViewModel
    private lateinit var segmentAdapter: SegmentAdapter

    // UI组件
    private lateinit var btnRefresh: Button
    private lateinit var progressBar: ProgressBar
    private lateinit var tvError: TextView
    private lateinit var cardBookingInfo: CardView
    private lateinit var tvSegmentsTitle: TextView
    private lateinit var recyclerViewSegments: RecyclerView

    // 预订信息UI组件
    private lateinit var tvShipReference: TextView
    private lateinit var tvShipToken: TextView
    private lateinit var tvCanIssueTicket: TextView
    private lateinit var tvDuration: TextView
    private lateinit var tvExpiryTime: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_booking_list)

        initViews()
        initViewModel()
        initRecyclerView()
        observeViewModel()

        // 每次页面出现时调用数据提供者接口
        loadBookingData()
    }

    override fun onResume() {
        super.onResume()
        // 每次页面出现（不仅仅是首次创建）时都调用数据提供者接口
        println("BookingListActivity: onResume - 页面出现，调用数据提供者接口")
        loadBookingData()
    }

    private fun initViews() {
        btnRefresh = findViewById(R.id.btnRefresh)
        progressBar = findViewById(R.id.progressBar)
        tvError = findViewById(R.id.tvError)
        cardBookingInfo = findViewById(R.id.cardBookingInfo)
        tvSegmentsTitle = findViewById(R.id.tvSegmentsTitle)
        recyclerViewSegments = findViewById(R.id.recyclerViewSegments)

        // 预订信息UI组件
        tvShipReference = findViewById(R.id.tvShipReference)
        tvShipToken = findViewById(R.id.tvShipToken)
        tvCanIssueTicket = findViewById(R.id.tvCanIssueTicket)
        tvDuration = findViewById(R.id.tvDuration)
        tvExpiryTime = findViewById(R.id.tvExpiryTime)

        // 设置刷新按钮点击事件
        btnRefresh.setOnClickListener {
            refreshBookingData()
        }
    }

    private fun initViewModel() {
        // 使用AndroidViewModelFactory来创建AndroidViewModel
        val factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application)
        viewModel = ViewModelProvider(this, factory)[BookingViewModel::class.java]
    }

    private fun initRecyclerView() {
        segmentAdapter = SegmentAdapter(emptyList())
        recyclerViewSegments.apply {
            layoutManager = LinearLayoutManager(this@BookingListActivity)
            adapter = segmentAdapter
        }
    }

    private fun observeViewModel() {
        viewModel.bookingData.observe(this) { booking ->
            updateUI(booking)
        }

        viewModel.isLoading.observe(this) { isLoading ->
            updateLoadingState(isLoading)
        }

        viewModel.error.observe(this) { error ->
            updateErrorState(error)
        }
    }

    private fun loadBookingData() {
        println("BookingListActivity: 调用ViewModel加载预订数据")
        viewModel.loadBookingData()
    }

    private fun refreshBookingData() {
        println("BookingListActivity: 用户点击刷新按钮，强制刷新数据")
        viewModel.refreshBookingData()
    }

    private fun updateUI(booking: Booking?) {
        if (booking != null) {
            // 显示预订基本信息
            cardBookingInfo.visibility = View.VISIBLE
            tvSegmentsTitle.visibility = View.VISIBLE

            updateBookingInfo(booking)
            updateSegmentsList(booking)
        } else {
            // 隐藏UI组件
            cardBookingInfo.visibility = View.GONE
            tvSegmentsTitle.visibility = View.GONE
        }
    }

    private fun updateBookingInfo(booking: Booking) {
        tvShipReference.text = "船只参考号: ${booking.shipReference}"
        tvShipToken.text = "船只令牌: ${booking.shipToken}"
        tvCanIssueTicket.text = "可出票检查: ${if (booking.canIssueTicketChecking) "是" else "否"}"
        tvDuration.text = "持续时间: ${booking.duration}分钟"

        // 格式化过期时间
        val expiryTimeFormatted = try {
            val expiryTimeMillis = booking.expiryTime.toLong() * 1000
            val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
            dateFormat.format(Date(expiryTimeMillis))
        } catch (e: NumberFormatException) {
            booking.expiryTime
        }

        val isExpired = booking.isBookingExpired()
        val expiryStatus = if (isExpired) " (已过期)" else " (有效)"
        tvExpiryTime.text = "过期时间: $expiryTimeFormatted$expiryStatus"

        // 根据是否过期设置文字颜色
        if (isExpired) {
            tvExpiryTime.setTextColor(resources.getColor(android.R.color.holo_red_dark))
        } else {
            tvExpiryTime.setTextColor(resources.getColor(android.R.color.holo_green_dark))
        }
    }

    private fun updateSegmentsList(booking: Booking) {
        segmentAdapter.updateSegments(booking.segments)

        // 确保RecyclerView可见
        if (booking.segments.isNotEmpty()) {
            recyclerViewSegments.visibility = View.VISIBLE
        }
    }

    private fun updateLoadingState(isLoading: Boolean) {
        progressBar.visibility = if (isLoading) View.VISIBLE else View.GONE
        btnRefresh.isEnabled = !isLoading
        btnRefresh.text = if (isLoading) "加载中..." else "刷新"
    }

    private fun updateErrorState(error: String?) {
        if (error.isNullOrEmpty()) {
            tvError.visibility = View.GONE
        } else {
            tvError.visibility = View.VISIBLE
            tvError.text = error
        }
    }
}